<template>
  <div class="bill-list-container">
    <div class="page-header">
      <el-button @click="goHome" circle size="large" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h1>📊 {{ pageTitle }}</h1>
      <el-button v-if="!isViewingPartner" type="primary" @click="goToCreateBill" round>
        <el-icon><Plus /></el-icon>
        <span>记一笔</span>
      </el-button>
    </div>

    <!-- 日期和统计类型选择 -->
    <div class="date-filter-bar">
      <el-date-picker
        v-model="selectedDate"
        :type="datePickerType"
        :placeholder="datePickerPlaceholder"
        @change="handleDateChange"
        style="width: 200px;"
      />

      <el-radio-group v-model="statisticsType" @change="handleStatisticsTypeChange" size="small">
        <el-radio-button label="day">按天</el-radio-button>
        <el-radio-button label="month">按月</el-radio-button>
        <el-radio-button label="year">按年</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-label">{{ statisticsLabel }}总支出</div>
        <div class="stat-value">¥{{ formatAmount(stats.totalAmount) }}</div>
      </div>
      <div v-if="!isViewingPartner" class="stat-card my-stat">
        <div class="stat-label">我的支出</div>
        <div class="stat-value">¥{{ formatAmount(stats.myAmount) }}</div>
      </div>
      <div v-if="!isViewingPartner" class="stat-card partner-stat">
        <div class="stat-label">对方支出</div>
        <div class="stat-value">¥{{ formatAmount(stats.partnerAmount) }}</div>
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-select v-model="filterCategory" placeholder="全部分类" size="small" @change="loadBills">
        <el-option label="全部分类" value="" />
        <el-option v-for="cat in categories" :key="cat.value" :label="cat.label" :value="cat.value">
          <span>{{ cat.icon }} {{ cat.label }}</span>
        </el-option>
      </el-select>

      <el-select v-model="filterStatus" placeholder="全部状态" size="small" @change="loadBills">
        <el-option label="全部状态" value="" />
        <el-option label="正常" :value="1" />
        <el-option label="待审批" :value="0" />
        <el-option label="已拒绝" :value="2" />
      </el-select>
    </div>

    <!-- 账单列表 -->
    <div v-loading="loading" class="bill-list">
      <div v-if="bills.length === 0" class="empty-state">
        <el-empty description="暂无账单记录">
          <el-button type="primary" @click="goToCreateBill" round>立即记账</el-button>
        </el-empty>
      </div>

      <div v-else class="bill-items">
        <div
          v-for="bill in bills"
          :key="bill.id"
          :class="['bill-item', { 'my-bill': bill.isMine, 'partner-bill': !bill.isMine }]">

          <div class="bill-icon" @click="goToBillDetail(bill.id)">
            {{ getCategoryIcon(bill.category) }}
          </div>

          <div class="bill-info" @click="goToBillDetail(bill.id)">
            <div class="bill-purpose">{{ bill.purpose }}</div>
            <div class="bill-meta">
              <span class="bill-category">{{ bill.category }}</span>
              <span class="bill-date">{{ formatDate(bill.billDate) }}</span>
            </div>
          </div>

          <div class="bill-right">
            <div class="bill-amount">¥{{ formatAmount(bill.amount) }}</div>
            <el-tag
              v-if="bill.status === 0"
              type="warning"
              size="small">
              待审批
            </el-tag>
            <el-tag
              v-else-if="bill.status === 2"
              type="danger"
              size="small">
              已拒绝
            </el-tag>
            <el-tag
              v-else
              type="success"
              size="small">
              正常
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import { getBillList } from '@/api'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 获取路由参数
const targetUserId = ref(route.query.targetUserId ? Number(route.query.targetUserId) : null)
const targetUserName = ref(route.query.targetUserName || 'TA')

// 是否正在查看对方的账单
const isViewingPartner = computed(() => targetUserId.value !== null)

// 页面标题
const pageTitle = computed(() => {
  return isViewingPartner.value ? `${targetUserName.value}的账单` : '账单列表'
})

// 分类选项
const categories = [
  { value: '餐饮', label: '餐饮', icon: '🍔' },
  { value: '购物', label: '购物', icon: '🛍️' },
  { value: '交通', label: '交通', icon: '🚗' },
  { value: '娱乐', label: '娱乐', icon: '🎮' },
  { value: '医疗', label: '医疗', icon: '💊' },
  { value: '教育', label: '教育', icon: '📚' },
  { value: '住房', label: '住房', icon: '🏠' },
  { value: '其他', label: '其他', icon: '📦' }
]

// 响应式数据
const bills = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const filterCategory = ref('')
const filterStatus = ref('')

// 日期和统计类型
const selectedDate = ref(new Date())
const statisticsType = ref('month') // 'day', 'month', 'year'

// 统计数据
const stats = ref({
  totalAmount: 0,
  myAmount: 0,
  partnerAmount: 0
})

// 计算属性
const datePickerType = computed(() => {
  const typeMap = {
    day: 'date',
    month: 'month',
    year: 'year'
  }
  return typeMap[statisticsType.value]
})

const datePickerPlaceholder = computed(() => {
  const placeholderMap = {
    day: '选择日期',
    month: '选择月份',
    year: '选择年份'
  }
  return placeholderMap[statisticsType.value]
})

const statisticsLabel = computed(() => {
  const labelMap = {
    day: '当天',
    month: '本月',
    year: '本年'
  }
  return labelMap[statisticsType.value]
})

// 获取分类图标
const getCategoryIcon = (category) => {
  const cat = categories.find(c => c.value === category)
  return cat ? cat.icon : '📦'
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)

  if (d.toDateString() === today.toDateString()) {
    return '今天'
  } else if (d.toDateString() === yesterday.toDateString()) {
    return '昨天'
  } else {
    return d.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
  }
}

// 加载账单列表
const loadBills = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 添加分类筛选
    if (filterCategory.value) {
      params.category = filterCategory.value
    }

    // 添加状态筛选
    if (filterStatus.value !== '') {
      params.status = filterStatus.value
    }

    // 添加日期筛选
    if (selectedDate.value) {
      const date = new Date(selectedDate.value)

      if (statisticsType.value === 'day') {
        // 按天：获取当天的账单
        params.startDate = formatDateForApi(date)
        params.endDate = formatDateForApi(date)
      } else if (statisticsType.value === 'month') {
        // 按月：获取当月的账单
        const year = date.getFullYear()
        const month = date.getMonth()
        const firstDay = new Date(year, month, 1)
        const lastDay = new Date(year, month + 1, 0)
        params.startDate = formatDateForApi(firstDay)
        params.endDate = formatDateForApi(lastDay)
      } else if (statisticsType.value === 'year') {
        // 按年：获取当年的账单
        const year = date.getFullYear()
        const firstDay = new Date(year, 0, 1)
        const lastDay = new Date(year, 11, 31)
        params.startDate = formatDateForApi(firstDay)
        params.endDate = formatDateForApi(lastDay)
      }
    }

    // 如果正在查看对方的账单，添加 targetUserId 参数
    if (targetUserId.value) {
      params.targetUserId = targetUserId.value
    }

    const res = await getBillList(params)

    if (res.code === 200) {
      const currentUserId = userStore.userInfo?.id

      // 标记是否是我的账单
      bills.value = res.data.records.map(bill => ({
        ...bill,
        isMine: bill.userId === currentUserId
      }))

      total.value = res.data.total

      // 计算统计数据
      calculateStats()
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '加载失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期为 API 需要的格式 (YYYY-MM-DD)
const formatDateForApi = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 计算统计数据
const calculateStats = () => {
  const currentUserId = userStore.userInfo?.id

  let totalAmount = 0
  let myAmount = 0
  let partnerAmount = 0

  // 只统计状态为正常的账单
  bills.value.forEach(bill => {
    if (bill.status === 1) {
      const amount = Number(bill.amount)
      totalAmount += amount

      if (bill.userId === currentUserId) {
        myAmount += amount
      } else {
        partnerAmount += amount
      }
    }
  })

  stats.value = {
    totalAmount,
    myAmount,
    partnerAmount
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadBills()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadBills()
}

// 跳转到创建账单页面
const goToCreateBill = () => {
  router.push('/bill/create')
}

// 跳转到账单详情页面
const goToBillDetail = (billId) => {
  router.push(`/bill/${billId}`)
}

// 返回主页
const goHome = () => {
  router.push('/home')
}

// 处理日期变化
const handleDateChange = () => {
  currentPage.value = 1
  loadBills()
}

// 处理统计类型变化
const handleStatisticsTypeChange = () => {
  // 重置日期为当前日期
  selectedDate.value = new Date()
  currentPage.value = 1
  loadBills()
}

// 页面加载时获取数据
onMounted(() => {
  loadBills()
})
</script>

<style scoped>
.bill-list-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: bold;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.back-btn {
  background: white;
  border: none;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.2);
}

.date-filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding: 16px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.1);
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 16px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.1);
}

.stat-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #ff9a9e;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.bill-list {
  background: white;
  border-radius: 24px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(255, 154, 158, 0.15);
  min-height: 400px;
}

.bill-items {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.bill-item {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 16px;
  background: linear-gradient(135deg, #ffffff 0%, #fafafa 100%);
  border-radius: 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-left: 4px solid transparent;
  position: relative;
  box-shadow: 0 2px 12px rgba(255, 154, 158, 0.08);
}

.bill-item:hover {
  background: linear-gradient(135deg, #fff5f7 0%, #ffeef8 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(255, 154, 158, 0.15);
}

.bill-item:active {
  transform: translateY(0);
}

.bill-item.my-bill {
  border-left-color: #ff9a9e;
}

.bill-item.partner-bill {
  border-left-color: #a8dadc;
}

.bill-icon {
  font-size: 32px;
  width: 52px;
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ffffff 0%, #f8f8f8 100%);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
}

.bill-icon:hover {
  transform: scale(1.1) rotate(5deg);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.bill-info {
  flex: 1;
  cursor: pointer;
  min-width: 0;
}

.bill-purpose {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  line-height: 1.4;
}

.bill-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
  align-items: center;
}

.bill-category {
  padding: 2px 8px;
  background: rgba(255, 154, 158, 0.1);
  border-radius: 4px;
  color: #ff9a9e;
  font-weight: 500;
}

.bill-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  flex-shrink: 0;
}

.bill-amount {
  font-size: 20px;
  font-weight: bold;
  color: #ff9a9e;
  font-family: 'Arial', sans-serif;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-state {
  padding: 60px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bill-list-container {
    padding: 8px;
  }

  .page-header {
    margin-bottom: 16px;
  }

  .page-header h1 {
    font-size: 20px;
  }

  .back-btn {
    padding: 10px 16px;
  }

  .date-filter-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
    padding: 12px;
    border-radius: 14px;
    margin-bottom: 12px;
  }

  /* 移动端统计卡片优化 */
  .stats-cards {
    grid-template-columns: 1fr;
    gap: 10px;
    margin-bottom: 16px;
  }

  .stat-card {
    padding: 14px;
    border-radius: 14px;
  }

  .stat-label {
    font-size: 13px;
    margin-bottom: 6px;
  }

  .stat-value {
    font-size: 20px;
  }

  /* 移动端筛选栏优化 */
  .filter-bar {
    flex-direction: column;
    gap: 8px;
    margin-bottom: 16px;
  }

  .bill-list {
    padding: 14px;
    border-radius: 20px;
  }

  /* 移动端账单项优化 */
  .bill-items {
    gap: 10px;
  }

  .bill-item {
    padding: 14px;
    border-radius: 14px;
    gap: 10px;
    box-shadow: 0 2px 8px rgba(255, 154, 158, 0.1);
    /* 移动端触摸优化 */
    -webkit-tap-highlight-color: transparent;
    touch-action: manipulation;
  }

  .bill-item:active {
    transform: scale(0.98);
    box-shadow: 0 1px 4px rgba(255, 154, 158, 0.15);
  }

  .bill-icon {
    width: 48px;
    height: 48px;
    font-size: 28px;
    border-radius: 10px;
    flex-shrink: 0;
  }

  .bill-info {
    flex: 1;
    min-width: 0; /* 防止文字溢出 */
  }

  .bill-purpose {
    font-size: 15px;
    font-weight: 600;
    margin-bottom: 6px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .bill-meta {
    gap: 8px;
    font-size: 11px;
  }

  .bill-right {
    flex-direction: column;
    align-items: flex-end;
    gap: 6px;
    flex-shrink: 0;
  }

  .bill-amount {
    font-size: 20px;
    font-weight: bold;
  }

  /* 标签优化 */
  .bill-right .el-tag {
    font-size: 11px;
    padding: 2px 8px;
    height: auto;
  }

  /* 移动端分页器优化 */
  .pagination {
    margin-top: 16px;
  }

  /* 移动端空状态优化 */
  .empty-state {
    padding: 40px 16px;
  }
}

/* 小屏手机适配 */
@media (max-width: 576px) {
  .bill-list-container {
    padding: 6px;
  }

  .page-header {
    flex-wrap: wrap;
    gap: 10px;
  }

  .page-header h1 {
    font-size: 17px;
    flex: 1;
  }

  .stat-value {
    font-size: 17px;
  }

  /* 小屏账单项优化 */
  .bill-items {
    gap: 8px;
  }

  .bill-item {
    padding: 12px;
    border-radius: 12px;
    gap: 8px;
  }

  .bill-icon {
    width: 44px;
    height: 44px;
    font-size: 26px;
  }

  .bill-purpose {
    font-size: 14px;
    margin-bottom: 5px;
  }

  .bill-meta {
    gap: 6px;
    font-size: 10px;
  }

  .bill-amount {
    font-size: 18px;
  }

  .bill-right .el-tag {
    font-size: 10px;
    padding: 1px 6px;
  }
}

/* 超小屏手机适配 */
@media (max-width: 375px) {
  .bill-item {
    padding: 10px;
  }

  .bill-icon {
    width: 40px;
    height: 40px;
    font-size: 24px;
  }

  .bill-purpose {
    font-size: 13px;
  }

  .bill-amount {
    font-size: 16px;
  }
}
</style>

